import Vue from 'vue';
import MessageComponent from './message.vue';
//创建实例，手动挂载
let MessageConstructor = Vue.extend(MessageComponent);//组件的初始化用extend方法
let instance;
let instances = [];
let seed = 1;
const Message = (options) => {
  //统一入口，每点一次创建一个实例
  let userOnClose = options.onClose;
  let id = 'message_' + seed++;

  options.onClose = function () {
    Message.close(id, userOnClose);
  };
  
  instance = new MessageConstructor({//给这个组件传入了data数据
    data: options
  });
  instance.id = id;
  instance.$mount();//表示挂载组件，挂载后的结果会放到instance.$el
  document.body.appendChild(instance.$el);

  //计算位置
  let verticalOffset = options.offset || 20;
  instances.forEach(item => {
    verticalOffset += item.$el.offsetHeight + 16;
  });
  instance.verticalOffset = verticalOffset;
  instance.visible = true;//扔到页面时，将属性visible改成true
  instances.push(instance);
  return instance;
}

['success', 'error', 'warning'].forEach(type => {
  Message[type] = function (options) {//Message.success
    options.type = type;//把success加到options里了
    return Message(options)
  }
})
Message.close = function (id, userOnClose) {
  let len = instances.length;
  let index = -1;
  let removedHeight;
  for (let i = 0; i < len; i++) {
    if (id === instances[i].id) {
      removedHeight = instances[i].$el.offsetHeight;
      index = i;
      if (typeof userOnClose === 'function') {
        userOnClose(instances[i]);
      }
      instances.splice(i, 1);
      break;
    }
  }
  if (len <= 1 || index === -1 || index > instances.length - 1) return;
  for (let i = index; i < len - 1; i++) {
    let dom = instances[i].$el;
    dom.style['top'] =
      parseInt(dom.style['top'], 10) - removedHeight - 16 + 'px';
  }
};

Message.closeAll = function () {
  for (let i = instances.length - 1; i >= 0; i--) {
    instances[i].close();
  }
};
export { Message }